package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.CatalogService;
import csu.web.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    private static final String SIGN_ON = "/WEB-INF/jsp/account/signon.jsp";
    private String workingItemId;
    private Cart cart;
    private Account account;
    private CatalogService catalogService;
    private CartService cartService;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        workingItemId = req.getParameter("workingItemId");

        HttpSession session = req.getSession();
        cart = (Cart)session.getAttribute("cart");

        account = (Account) session.getAttribute("loginAccount");
        if(account == null){
            // 跳转到登录界面
            req.getRequestDispatcher(SIGN_ON).forward(req,resp);
        }

        if(cart == null){
            cart = new Cart();
        }

        if(account!=null)
        {
            if(cart.containsItemId(workingItemId)){
                cart.incrementQuantityByItemId(workingItemId);
            }else{
                catalogService = new CatalogService();
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item,isInStock);
            }
        }


        session.setAttribute("cart",cart);

        Account account = (Account) session.getAttribute("loginAccount");
        cartService = new CartService();


        if(account != null) {
            cartService.insertItem(account.getUsername(),workingItemId);
            String strUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + req.getServletPath() + "?" + req.getQueryString();
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") +"用户" +account.getUsername()+  "  "+"添加商品" + workingItemId + "至购物车";
            logService.insertLogInfo(account.getUsername(),logInfo);
        }

        req.getRequestDispatcher(CART_FORM).forward(req,resp);

    }
}
